// 图片懒加载
var imgs = document.getElementsByName("img");

function throttle(func, time) {
    let timer = null;
    return function (...args) {
        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
                func.apply(this, args)
            }, time)
        }
    }
}

window.addEventListener("scroll", throttle(lazyload))

function lazyload() {
    // 可见内容区域
    var seeHeight = window.innerHeight;
    // 滚动条距离顶部高度
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].offsetTop < seeHeight + scrollTop) {
            if (imgs[i].getAttribute("src") === "loading.gif") {
                imgs[i].src = imgs[i].getAttribute("data-src")
            }
        }
    }
}


// 利用observer  intersectionObserver
let LazyImageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach((entry, index) => {
        let LazyImg = entry.target;
        if (entry.intersectionRatio > 0) {
            if (LazyImg.getAttribute("src") === "load.gif") {
                LazyImg.src = LazyImg.getAttribute("data-src")
            }
            LazyImageObserver.unobserve(LazyImg)
        }
    })

    for (let i = 0; i < imgs.length; i++) {
        LazyImageObserver.observe(imgs[i])
    }
})